package com.wsoft.utils;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 功能描述
 *
 * @author: juiet
 * @date: 2024年08月24日 16:20
 */
public class LangUtil {

    /**
     * 大括号内容模型
     */
    private static Pattern pattern = Pattern.compile("\\{([^\\}]+)\\}");

    /**
     *
     * @return
     */
    public static String tranLang(String responseBody){
        List<String> list = findStringsInsideBracket(responseBody);
        String lang = LocaleContextHolder.getLocale().getLanguage();
        if(list!=null && list.size()>0){
            for(String str: list){
                String modelStr = lang+"_"+str;
                String tranStr = ResourceUtil.mutiLangMap.get(modelStr);
                if(StringUtils.hasText(tranStr)){
                    responseBody = responseBody.replace("["+str+"]",tranStr);
                }
            }
        }
        return responseBody;
    }

    /**
     * 去除中括号内的内容
     * @param text
     * @return
     */
    public static List<String> findStringsInsideBracket(String text) {
        List<String> stringsInsideBraces = new ArrayList<>();

        if(StringUtils.hasText(text)){
            String[] texts = text.split("]");
            for(int i=0;i<texts.length;i++){
                String value = splitBracket(texts[i]);
                if(StringUtils.hasText(value) && !text.endsWith(value)) {
                    stringsInsideBraces.add(value);
                }
            }
        }
        return stringsInsideBraces;
    }

    public static String splitBracket(String text){
        if(StringUtils.hasText(text)){
            String[] s = text.split("\\[");
            return s.length>=2?s[s.length-1]:null;
        }
        return null;
    }

    public static void main(String[] args) {
        String input = "{\"[test]code\":200[test],\"data\":\"[test]\",\"message\":\"操作成功\"}";
        String str = input.replace("[test]","test");
        System.out.println(str);
    }

    public static List<String> findStringsInsideBraces(String text) {
        List<String> stringsInsideBraces = new ArrayList<>();
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            // 添加非括号字符
            stringsInsideBraces.add(matcher.group(1));
        }

        return stringsInsideBraces;
    }


    public static void main2(String[] args) {
        String input = "This is a {sa{mp}le} string with {multiple} {bra{ces}.";
        List<String> insideBraces = findStringsInsideBraces(input);

        // 打印结果
        insideBraces.forEach(System.out::println);
    }
}
